<template>
    <div ref="mainRef" class="mainRef"></div>
</template>

<script lang="ts" setup>
import * as echarts from 'echarts'
import { onMounted, onUnmounted, ref, watch } from 'vue'

interface IProps { chartOption: echarts.EChartsOption, theme?: string }
const props = defineProps<IProps>()

const mainRef = ref()

let myChart: echarts.ECharts | null = null
const init = () => {
    myChart = echarts.init(mainRef.value, props.theme ? props.theme : 'dark', { renderer: 'svg' })
    const option = props.chartOption
    myChart.setOption(option)
    window.addEventListener('resize', resizeFn)
}
const resizeFn = () => {
    myChart!.resize()
}

onMounted(() => {
    watch(props, (newData) => {
        if (myChart) {
            myChart?.dispose()
            init()
            // myChart.setOption(newData)
        } else {
            init()
        }
    })
})


onUnmounted(() => {
    // 销毁 echart 实例，释放资源
    myChart?.dispose()
    window.removeEventListener('resize', resizeFn);
})
</script>

<style lang="scss">
.mainRef {
    width: 100%;
    height: 100%;
}
</style>